package algorithm.leetcode;

import Utils.JsonUtils;

import java.util.*;
import java.util.stream.Collectors;

public class LeetCode_1418_displayTable {
    public static List<List<String>> displayTable(List<List<String>> orders) {
        SortedMap<Integer, Map<String, Integer>> tables = new TreeMap<>();
        SortedSet<String> dishes = new TreeSet<>();
        orders.forEach(order -> {
            Integer tableNum = Integer.parseInt(order.get(1));
            String dishName = order.get(2);
            dishes.add(dishName);
            Map<String, Integer> freqMap = tables.getOrDefault(tableNum, new HashMap<>());
            Integer dishNum = freqMap.getOrDefault(dishName, 0);
            freqMap.put(dishName, dishNum + 1);
//            if (freqMap != null) {
//                Integer freq = freqMap.get(dishName);
//                freqMap.put(dishName, (freq == null) ? 1 : freq + 1);
//            }
//            else {
//                freqMap = new HashMap<>();
//                freqMap.put(dishName, 1);
//            }
            tables.put(tableNum, freqMap);
        });
        List<List<String>> res = new ArrayList<>();
        res.add(new ArrayList<>(dishes));
        res.get(0).add(0, "Table");
        tables.forEach((numTable, order) -> {
            List<String> temp = dishes.stream()
                    .map(dishName -> order.getOrDefault(dishName, 0).toString())
                    .collect(Collectors.toList());
            temp.add(0, numTable.toString());
            res.add(temp);
        });

        return res;
    }

    public static void main(String[] args) {
        String req = "[[\"David\",\"3\",\"Ceviche\"],[\"Corina\",\"10\",\"Beef Burrito\"],[\"David\",\"3\",\"Fried Chicken\"],[\"Carla\",\"5\",\"Water\"],[\"Carla\",\"5\",\"Ceviche\"],[\"Rous\",\"3\",\"Ceviche\"]]";
        List<List<String>> orders = JsonUtils.parse(req, List.class);
        List<List<String>> res = displayTable(orders);
    }
}
